﻿using K3Cloud.WebApi.Core.IoC.Attributes;
using K3Cloud.WebApi.Core.IoC.K3Client;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;

namespace K3Cloud.WebApi.Core.IoC.Extensions
{
    /// <summary>
    /// Extensions 提供各种扩展方法。
    /// 包含类型别名获取、字符编码转换、HTTP客户端配置等功能。
    /// </summary>
    public static class Extensions
    {
        #region 类型别名
        /// <summary>
        /// 获取对象的类型别名。
        /// 优先获取AliasAttribute特性值，否则返回类型名。
        /// </summary>
        /// <param name="obj">目标对象</param>
        /// <returns>别名或类型名</returns>
        [DebuggerStepThrough]
        public static string GetAlias(this object obj)
        {
            return obj.GetType().GetCustomAttribute<AliasAttribute>()?.Name ?? obj.GetType().Name;
        }

        /// <summary>
        /// 获取类型的别名（AliasAttribute特性值）。
        /// </summary>
        /// <param name="t">目标类型</param>
        /// <param name="inherit">是否继承</param>
        /// <returns>别名或类型名</returns>
        [DebuggerStepThrough]
        public static string GetAlias(this Type t, bool inherit = false)
        {
            return t == null ? string.Empty : t.GetCustomAttribute<AliasAttribute>(inherit)?.Name ?? t.Name;
        }
        #endregion

        /// <summary>
        /// 将\u1234类型的Unicode字符转化成汉字。
        /// </summary>
        public static string DeCode(string str)
        {
            Regex regex = new(@"\\u(\w{4})");
            string result = regex.Replace(str, delegate (Match m)
            {
                string hexStr = m.Groups[1].Value;
                string charStr = ((char)int.Parse(hexStr, System.Globalization.NumberStyles.HexNumber)).ToString();
                return charStr;
            });
            return result;
        }

        /// <summary>
        /// 可空类型转换
        /// </summary>
        [DebuggerStepThrough]
        public static Type ParseNullableToType(this Type source)
        {
            if (source.IsGenericType && source.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                NullableConverter nullableConverter = new(source);
                source = nullableConverter.UnderlyingType;
            }
            return source;
        }
        /// <summary>
        /// foreach 空检查
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static IEnumerable<T> CheckNull<T>(this IEnumerable<T> list)
        {
            return list ?? [];
        }

        public static IHttpClientBuilder AddDefaultHttpClient(this IServiceCollection services, CookieContainer? _cookie = default)
        {
            return services.AddHttpClient<K3HttpService>()
                 .ConfigurePrimaryHttpMessageHandler((sp) =>
                 {
                     HttpClientHandler handler = new()
                     {
                         CookieContainer = _cookie ?? new CookieContainer(),
                         UseProxy = false,
                         AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
                     };
                     return handler;
                 }).AddTransientHttpErrorPolicy(policyBuilder =>
                    policyBuilder.WaitAndRetryAsync(5, retryNumber => TimeSpan.FromMilliseconds(600))
                 );
        }
    }
}
